<template>
  <el-form :rules="rules" :model="users" label-width="200px" ref="editRef">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="users.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="users.password" show-password />
    </el-form-item>
    <el-form-item label="真实姓名" prop="realName">
      <el-input v-model="users.realName" />
    </el-form-item>
    <el-form-item label="所属科室" prop="section">
      <el-input v-model="users.section" />
    </el-form-item>
    <el-form-item label="电话" prop="phone">
      <el-input v-model="users.phone" />
    </el-form-item>
    <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="users.sex">
        <el-radio label="男" />
        <el-radio label="女" />
      </el-radio-group>
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input v-model="users.age" />
    </el-form-item>
    <el-form-item label="地址" prop="address">
      <el-input v-model="users.address" />
    </el-form-item>
    <el-form-item label="头像" prop="avatarUrl">
      <el-upload class="avatar-uploader" :action="actionUrl" :headers="uploadHeaders" :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload" :auto-upload="false" :data="users" :method="uploadMethod" ref="uploadRef">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item label="邮箱" prop="mailbox">
      <el-input v-model="users.mailbox" />
    </el-form-item>
    <el-form-item label="注册日期" prop="birthday">
      <el-date-picker v-model="users.birthday" type="datetime" placeholder="选择注册时间" />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-switch v-model="users.status" />
    </el-form-item>
  </el-form>
</template>

<script>
import { findMembers, delMembers, modifyMember, addMembersFile, addMembers } from '../../api/member'
export default {
  name: 'EditDoctor',
  data() {
    return {
      users: {
        username: "",
        password: "",
        realName: "",
        section: "",
        phone: "",
        age: "",
        sex: "",
        address: "",
        mailbox: "",
        birthday: "",
      },
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
        section: [{ required: true, message: "请输入所属科室", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话号码", trigger: "blur" }],
        age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        mailbox: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        birthday: [{ required: true, message: "请选择注册时间", trigger: "blur" }],
      },
      imageUrl: '',
      avatarUrl: '',
      uploadHeaders: {
        Authorization: `Bearer ${sessionStorage.getItem('token')}`,
      },
      uploadMethod: 'post',
      actionUrl: '/api/v1/doctor/users',
      hasFileUpload: false,
    }
  },
  emits: ['success'],

  methods: {
    handleAvatarSuccess(response, uploadFile) {
      console.log('上传成功:', response)
      // 将上传成功服务端的地址保存到 user 数据中
      this.users.avatarUrl = response.data.file
      // 将上传文件的路径资源信息保存到 imageUrl 中
      this.imageUrl = URL.createObjectURL(uploadFile.raw)
    },
    /**
     * 文件上传前，验证格式与大小
     * @param {*} rawFile 原始文件
     */
    beforeAvatarUpload(rawFile) {
      if (!rawFile.type.includes('image/')) { // 判断是否为图片类型
        ElMessage.error('Avatar picture must be JPG or PNG format!')
        return false
      } else if (!/^(image\/jpeg|image\/png)$/.test(rawFile.type)) { // 判断文件类型是否为 jpeg 或 png
        ElMessage.error('Avatar picture must be JPG or PNG format!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) { // 文件大小，小于 2MB 可上传
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
      }
      this.hasFileUpload = true // 判断是否有文件需要上传
      return true
    },

    // 表单校验，校验通过后，返回表单中绑定的数据
    async validate() {
      try {
        await this.$refs.editRef.validate()
        if (this.hasFileUpload) {
          // 手动提交上传文件
          this.$refs.uploadRef.submit()
          console.log('上传...')
        } else {
          console.log('users.id:', this.users._id)
          if (this.users._id) { // 修改
            modifyMember(this.users)
            findMembers()
          } else { // 添加
            addMembers(this.users)
          }
        }
        this.$emit('success')
        // return this.users
      } catch (error) {
        return Promise.reject(error)
      }
    },


    // async validate() {
    //   try {
    //     await this.$refs.editRef.validate()
    //     if (this.hasFileUpload) {
    //       // 手动提交上传文件
    //       await this.$refs.uploadRef.upload()
    //       console.log('上传...')
    //     }
    //     console.log('users.id:', this.users.id)
    //     if (this.users.id) { // 修改
    //       modifyMember(this.users)
    //       findMembers()
    //     } else { // 添加
    //       addMembersFile(this.users)
    //     }
    //     this.$emit('success')
    //   } catch (error) {
    //     return Promise.reject(error)
    //   }
    // },


    // 表单数据回显
    setFieldsValue(filelds) {
      this.imageUrl = filelds.avatarUrl ?? ''
    },
    setData(user) {
      // this.actionUrl = '/api/v1/doctor/users'
      this.uploadMethod = 'put'
      this.users = { ...user }
      console.log('修改:', this.users)
    },
  }
}

</script>

<style lang="less" scoped>
.el-form {
  text-align: center;
}

.el-form-item {
  margin-left: -80px;
}

:deep(.el-upload) {
  width: 100px;
  height: 100px;

  img {
    width: 100%;
    height: 100%;
  }
}
</style>
